/*
 * Copyright (c) 2025 UCT Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/

import { hilog } from '@kit.PerformanceAnalysisKit';
import { edit_TableName_Params, _table_name_, _TableName_ItemView, getDB, Env, _TableName_Response
, SearchParams, _TableName_QueryParams, _TableName_Formated, getCloudSelectFilter } from 'commondb';
import {
  ColumnType,
  EventParamsBaseType,
  IEventSender,
  ILog,
  Migration,
  Rdb,
  RdbDao,
  RdbDatabase
} from 'rdbstore';
import { ComponentContent } from '@kit.ArkUI';
import { AppStorageV2, PersistenceV2 } from '@kit.ArkUI';
import { common } from '@kit.AbilityKit';
import axios, {AxiosError, AxiosResponse, AxiosProgressEvent, InternalAxiosRequestConfig, AxiosRequestConfig} from '@ohos/axios'

let contentNode: ComponentContent<MyCustomDialog>

class DialogParams {
  mode: string = "";
  visible: boolean = false
  editJsonData: _table_name_ = new _table_name_();
  onCancel?: () => void | Promise<void> | undefined = undefined;
  onConfirm?: (_table_name_Obj: _table_name_ , editData: string) => void | Promise<void> | undefined = undefined;
  constructor(mode: string , visible: boolean, editJsonData: _table_name_, onCancel?: () => void | Promise<void> | undefined, onConfirm?: (_table_name_Obj: _table_name_ , editData: string) => void | Promise<void> | undefined) {
    this.mode = mode;
    this.visible = visible;
    this.editJsonData = editJsonData;
    this.onCancel = onCancel;
    this.onConfirm = onConfirm;
  }
}

@Builder
function buildBackConfirmDialog(dialogParams: DialogParams) {
  MyCustomDialog({ mode: dialogParams.mode,visible: dialogParams.visible,editJsonData: dialogParams.editJsonData, onCancel: dialogParams.onCancel, onConfirm: dialogParams.onConfirm })
}

@ComponentV2
export struct Cloud_TableName_ListView {
  private context = getContext(this) as common.UIAbilityContext;
  @Local mode:string = 'add';   // 'add' | 'edit'
  @Local visible: boolean = false
  @Local editJsonData:_table_name_ = new _table_name_();
  @Local searchValue: string = '';
  @Consumer() _table_name_List: _table_name_[] =  [new _table_name_()];
  @Local selectKeyText: string = "id"
  @Local selectKeyIndex: number = 0
  @Local selectFilterText: string = "equals"
  @Local selectFilterIndex: number = 0
  @Computed
  get _table_name_Count() {
    return this._table_name_List.length;
  }

  @Monitor('visible')
  visibleOnChange() {
    if (this.visible) {
      this.getUIContext().getPromptAction().openCustomDialog(contentNode, {
        onWillDismiss: (data) => {
        }
      })
    } else {
      this.getUIContext().getPromptAction().closeCustomDialog(contentNode)
    }
  }

    // 搜索实体
  async search_TableName_(value: string) {
    let searchParams = new _TableName_QueryParams(value);
    let searchParam: string = `?sort=id&filter={"${this.selectKeyText}":{"${this.selectFilterText}":"${value}"}}`; //searchParams.toQueryParams();
    
    const result = await _table_name_.apiGet_TableName_List(  //服务端API需登录鉴权token，登陆后可获取到返回值
      0,
      10,
      searchParam  //searchParams.toQueryParams() //todo:先用简单灵活的字符串拼装，有空在做标准化封装
    );
    if (result) {
      const rawResponse = result.getRawResponse() as AxiosResponse<_TableName_Response, Record<string, never>>
      //API接口Json数据转换为前端数据库模型类型
      this._table_name_List = rawResponse.data._table_name_s.map(item => _table_name_.fromJson(JSON.stringify(item)));

    }
  }

  // 新增实体
  async add_TableName_(_table_name_ToAdd: _table_name_) {
    const _table_name_WithoutEmpty = _table_name_.removeEmpty(_table_name_ToAdd);
    _table_name_.apiAdd_TableName_(_table_name_WithoutEmpty)

    // 更新列表
    this._table_name_List = [...this._table_name_List, _table_name_ToAdd];
  }

  // 更新实体
  async update_TableName_(_table_name_ToUpdate: _table_name_, editData: string) {
    const editParams: edit_TableName_Params = JSON.parse(editData);
    const _table_name_WithoutNull = _table_name_.removeNull(editParams);
    _table_name_.apiEdit_TableName_(_table_name_WithoutNull)
    
    // 更新列表中的实体
    this._table_name_List = this._table_name_List.map(item => 
      item.id === _table_name_ToUpdate.id ? _table_name_ToUpdate : item
    );
  }

  // 删除实体
  async delete_TableName_(_table_name_ToDelete: _table_name_) {
    _table_name_.apiDelete_TableName_({id:_table_name_ToDelete.id}) ;//删除服务端数据

    // 从列表中移除
    this._table_name_List = this._table_name_List.filter(item => item.id !== _table_name_ToDelete.id);
  }

  async get_TableName_Count(): Promise<number> {
    let db: RdbDatabase = getDB(Env.DATABASE_UCTOO_NAME);
    let _table_name_Dao: RdbDao<_table_name_> = await db.getDao(_table_name_)
    return _table_name_Dao.getCount();
  }

  onCancel(): void {
    this.visible = false;
  }

  //some extra task
  async onConfirm(_table_name_Obj: _table_name_ , editData: string): Promise<void> {
    try {
      let db: RdbDatabase = getDB(Env.DATABASE_UCTOO_NAME);
      let _table_name_Dao: RdbDao<_table_name_> = await db.getDao(_table_name_);

      if(this.mode == 'add'){
          await this.add_TableName_(_table_name_Obj as _table_name_);
      } else if(this.mode == 'edit'){
          await this.update_TableName_(_table_name_Obj as _table_name_, editData);
      }

    } catch (error) {
      console.error('Failed to save entity:', error);
    } finally {
      this.visible = false;
    }
  }

  async aboutToAppear() {
  }

  async onPageShow() {
  }

  // 在自定义组件即将析构销毁时将dialogControlle置空
  aboutToDisappear() {
  }

  prepareInsertData() {
  }

  prepareEditData(item:_table_name_) {
  }

  build() {
    Column() {
      Text(`cloud-_table_name_  ${getContext(this).resourceManager.getStringSync($r('app.string.count').id)}：${this._table_name_Count}`)
        .margin({ left: 10, bottom: 2 })

      Row() {
        Button($r('app.string.add'))
          .onClick(() => {
            this.mode = 'add';
            this.editJsonData = new _table_name_();
            
            //add新增可以用原型数据初始化对话框
            contentNode = new ComponentContent(this.getUIContext(), wrapBuilder(buildBackConfirmDialog),
              new DialogParams(this.mode, this.visible, this.editJsonData, () => this.onCancel(),async (_table_name_Obj: _table_name_, editData: string) => this.onConfirm(_table_name_Obj, editData) ))

            this.visible = !this.visible
          })
          .type(ButtonType.ROUNDED_RECTANGLE)
          .margin({ left: 'auto' })
        Button($r('app.string.reset'))
          .onClick(async () => {
            const result = await _table_name_.apiGet_TableName_List(  //服务端API需登录鉴权token，登陆后可获取到返回值
              0,
              10,
              ''
            );
            if (result) {
              const rawResponse = result.getRawResponse() as AxiosResponse<_TableName_Response, Record<string, never>>
              this._table_name_List = rawResponse.data._table_name_s.map(item => _table_name_.fromJson(JSON.stringify(item)));
            }
          })
          .type(ButtonType.ROUNDED_RECTANGLE)
          .margin({ left: 'auto' })
      }
      .width('100%')
      .padding(2)
      Row(){
        Column() {
          Select(_table_name_.getSelectKey())
            .height("36vp")
            .borderRadius(0)
            .selected(this.selectKeyIndex)
            .value(this.selectKeyText)
            .align(Alignment.Center)
            .font({ size: 20, weight: 500 })
            .fontColor('#182431')
            .selectedOptionFont({ size: 20, weight: 400 })
            .optionFont({ size: 20, weight: 400 })
            .backgroundColor(Color.Transparent)
            .responseRegion({ height: "38vp", width: "80%", x: '10%', y: '6vp' })
            .onSelect((selectKeyIndex: number, selectKeyText?: string | undefined) => {
              console.info('Select:' + selectKeyIndex)
              this.selectKeyIndex = selectKeyIndex;
              if (selectKeyText) {
                this.selectKeyText = selectKeyText;
              }
            })
        }.width('50%').height(36)
        Column() {
          Select(getCloudSelectFilter())
            .height("36vp")
            .borderRadius(0)
            .selected(this.selectFilterIndex)
            .value(this.selectFilterText)
            .align(Alignment.Center)
            .font({ size: 20, weight: 500 })
            .fontColor('#182431')
            .selectedOptionFont({ size: 20, weight: 400 })
            .optionFont({ size: 20, weight: 400 })
            .backgroundColor(Color.Transparent)
            .responseRegion({ height: "38vp", width: "80%", x: '10%', y: '6vp' })
            .onSelect((selectFilterIndex: number, selectFilterText?: string | undefined) => {
              console.info('Select:' + selectFilterIndex)
              this.selectFilterIndex = selectFilterIndex;
              if (selectFilterText) {
                this.selectFilterText = selectFilterText;
              }
            })
        }.width('50%').height(36)
      }
      .width('100%')
      .padding(2)
      Row() {
        Search({value: $$this.searchValue, placeholder: $r('app.string.search_placeholder') })
          .searchButton('search')
          .onSubmit((value: string) => this.search_TableName_(value))
      }
      .width('100%')
      .padding(2)
      // 实体列表
      List() {
        Repeat<_table_name_>(this._table_name_List.filter(_table_name_ => !_table_name_.deleted_at))
          .each((obj: RepeatItem<_table_name_>) => {
          ListItem() {
            _TableName_ItemView({
                _table_name_Item: obj.item,
                delete_TableName_: async () => {
                  // 处理删除
                  this.delete_TableName_(obj.item)
                },
                edit_TableName_: () => {
                  // 处理编辑
                  this.mode = 'edit';
                  this.editJsonData = obj.item; //edit需要用当前item数据初始化对话框

                  //this.prepareEditData(obj.item.toEntity())
                  //自定义对话框，
                  contentNode = new ComponentContent(this.getUIContext(), wrapBuilder(buildBackConfirmDialog),
                    new DialogParams(this.mode, this.visible, this.editJsonData, () => this.onCancel(),async (_table_name_Obj: _table_name_ , editData: string) => this.onConfirm(_table_name_Obj, editData) ))
                  this.visible = true;
                }
              })
            }
          })
      }
      .width('100%')
      .height('100%')
      .padding({ left: 16, right: 16 })
      .layoutWeight(1)
    }
    .width('100%')
    .height('100%')
    .backgroundColor('#F5F5F5')
  }
}


//V2版自定义弹窗
@ComponentV2
struct MyCustomDialog {
  @Param mode: string = '';
  @Param visible: boolean = false;
  @Param editJsonData:_table_name_ = new _table_name_();
  // 弹窗交互事件参数，点击确认和取消按钮时的回调函数
  @Param onCancel?: () => void | Promise<void> | undefined = undefined;
  @Param onConfirm?: (_table_name_Obj: _table_name_, editData: string) => void | Promise<void> | undefined = undefined;
  @Local JsonString:string = '';

  build() {
    Column({ space: 12 }) {
      TextArea({ text: this.editJsonData.toString(), placeholder: $r('app.string.add_table_data_json') })
        .fontSize(20).margin({ top: 10, bottom: 10 }).height(300)
        .onChange((value: string) => {
          this.JsonString = value
        })
      Row() {
        Button($r('app.string.cancel'))
          .onClick(async () => {
            this.onCancel?.();
          })
          .margin({ right: 20 })
        Button($r('app.string.confirm'))
          .onClick(async () => {
            if(this.mode == 'add'){
              const _table_name_Obj = _table_name_.fromJson(this.JsonString);
              await this.onConfirm?.(_table_name_Obj, this.JsonString);
            } else if(this.mode == 'edit'){
              const _table_name_Obj = _table_name_.fromJson(this.JsonString);
              await this.onConfirm?.(_table_name_Obj, this.JsonString);
            }
          })
      }
      .justifyContent(FlexAlign.Center)
    }
    .padding(24)
    .backgroundColor(Color.White)
  }
}
// 弹窗end